const huaweiYun = require('../config/huaweiCloud')
const DB = require('../config/Sequelize')
const BackCode = require("../utils/BackCode");
const codeEnum = require('../utils/CodeEnum');
const SecretTool = require('../utils/SecretTool');

const getPlayUrlService = {
    get_play_url: async (req) => {
        const {episodeId, token} = req
        // console.log('token: ', token);
        console.log('episodeId: ', episodeId);
        if(!episodeId || !token) {
            return BackCode.buildError('缺少必要参数')
        }
        //查找对于的集信息
        const episode = await DB.Episode.findOne({where: {id: episodeId}, raw: true})
        console.log('episode: ', episode);
        if(!episode) {
            return BackCode.buildError(codeEnum.COURSE_VIDEO_VOD_TYPE_NO_EXIST)
        }
        let tokenUser = SecretTool.jwtVerify(token);
        console.log('tokenUser: ', tokenUser);
        if(episode.free === 1){
            //不是免费，则需要判断他是否购买过
            let order = await DB.ProductOrder.findOne({where: {account_id: tokenUser.id,product_id: episode.product_id}})
            console.log('order: ', order);
            if(!order) {
                return BackCode.buildError(codeEnum.COURSE_MATERIAL_NO_PERMISSION)
            }
        }
        // 查询对于的id
        let url = await huaweiYun.getVideoUrl(episode.hwyun_id)
        console.log('url: ', url);
        return BackCode.buildSuccessAndData({data: {playResult: (url[0]),episodeId}})
    },
}
module.exports = getPlayUrlService